﻿using Assets.Script.BattleSystem.Core;
using Assets.Script.NetSystem.Battle.Core;
using LiteNetLib;
using LiteNetLib.Utils;
using Newtonsoft.Json;
using SimpleTools.Json;
using SimpleTools.Net.SimpleServer.UDP;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Script.NetSystem.Core;
using Script.NetSystem.Services.RoomAndBattle.BattleService.Handler;
using Script.NetSystem.Services.RoomAndBattle.BattleService.Interfaces;
using Script.UiSystem;
using UnityEngine;
using Assets.BattleSystem.EnemyConfigs;
using Assets.Script.Human.Player.Config;

namespace Script.NetSystem.Services.RoomAndBattle.BattleService
{
    public class BattleClient:BaseClient<BattleClient,IBattleHandler>
    {
        public int nowFrame;

        public BattleManager BattleManager;

        public BattleClient(int port, string key, ConnectSuccess onConnectSuccess, Action pollHandler) : base(port, key, onConnectSuccess, pollHandler,false)
        {
           
        }

        public void BattleScenceLoadEnd(CaseSpawnConfig caseConfig,RoleData[] roles)
        {
            BattleManager = new BattleManager(caseConfig, roles);
        }

        #region 帧同步

        private List<ISyncFrame> syncs = new List<ISyncFrame>();
        private List<ISyncFrame> addSyncs = new List<ISyncFrame>();
        private List<ISyncFrame> removeSyncs = new List<ISyncFrame>();

        private void SyncFrame()
        {
            syncs.AddRange(addSyncs);//增加同步对象

            foreach (var item in removeSyncs)//移除同步对象
            {
                syncs.Remove(item);
            }

            addSyncs.Clear();
            removeSyncs.Clear();

            syncs.ForEach((s) => { s.SyncFrame(); });//调用所有同步逻辑
        }
        public void AddSync(ISyncFrame sync)
        {
            addSyncs.Add(sync);
        }

        public void RemoveSync(ISyncFrame sync)
        {
            removeSyncs.Add(sync);
        }

        #endregion


        public void Handler(BattleManager battleManager,JsonData jsonData)
        {
            SyncFrame();
            nowFrame = jsonData.GetInt("frame");
            //todo 更新服务器时间
        }

        protected override Type[] GetHandlerTypes()
        {
            return new Type[] { typeof(Setpos) };
        }

        protected override BattleClient GetThisClient()
        {
            return this;
        }
        // public override IEnumerator PollTask()
        // {
        //     while (true)
        //     {
        //         BattleController.Instance.PollHandler.Invoke();
        //         client.Poll();
        //         yield return new WaitForSeconds(0.015f);
        //     }            
        // }
        
        public void ClientSend(NetDataWriter writer)
        {
            client.Send(writer);
        }
        
    }
}
